<template>
  <div class="activity-body">
    <div class="activity-ad"></div>
    <div class="condition-brand-box" v-if="openedActList && openedActList.brandVOS &&openedActList.brandVOS.length">
      <div class="brand-head-box activity-head-box">
        <span class="smalltitle">品牌折扣</span>
        <span v-show="fielsStatus !== 2" class="text-time">{{timerText}}</span>
        <div class="acti_entry_timer" v-if="timerresult">
          <template v-if="dayNum > 0">
            <span class="week-time">{{timerresult.substr(0,1)}}</span>
            <span class="timer-text">天</span>
          </template>
          <template v-else>
          <span class="week-time">{{timerresult.substr(2,2)}}</span>
          <span class="week-colon">:</span>
          <span class="week-time">{{timerresult.substr(5,2)}}</span>
          <span class="week-colon">:</span>
          <span class="week-time">{{timerresult.substr(8,2)}}</span>
          </template>
        </div>
      </div>
      <div class="txt-center brand-alternative-box">
        <span class="b-item" :class="{'active': brandIds === item.id}" v-for="(item, index) in openedActList.brandVOS" :key="index" @click="chooseCon(item.id, index)">
          品牌:
          <img :src="prefixImg + item.image" class="brandimg"/>
          {{item.name}}
        </span>
      </div>
    <!-- 筛选条件 -->
    <section class="category-box knife_container">
      <div class="condition-wrapper">
        <div class="condition-box" v-show="categoryName || others || searchInput">
          <span class="bread_a">全部:</span>
          <a href="javascript:void(0)" class="condition-txt" v-show="categoryName">
            <i class="el-icon-arrow-right"></i>
            <span>{{categoryName}}</span>
            <i class="el-icon-error" @click="clearCon('categoryName')"></i>
          </a>
          <a href="javascript:void(0)" class="condition-txt" v-show="others">
            <i class="el-icon-arrow-right"></i>
            <span>{{others}}</span>
            <i class="el-icon-error" @click="clearCon('others')"></i>
          </a>
          <a href="javascript:void(0)" class="condition-txt" v-show="searchInput">
            <i class="el-icon-arrow-right"></i>
            <span>{{searchInput}}</span>
            <i class="el-icon-error" @click="clearCon('searchInput')"></i>
          </a>
        </div>
        <div class="activity-search-box search-pos">
          <i class="el-icon-search search_posi"></i>
          <input type="text" placeholder="搜索商品" v-model.trim="searchInput" @keydown.13="blurGetAllData" class="brand-input-box" ref="searchRef"/>
          <span class="search_sure" @click="getAllData">确定</span>
        </div>
      </div>
      <div class="category-item knife_container">
        <div class="category-row" v-if="categoryList.length > 0">
          <span class="category-tit">商品类目</span>
          <section class="category-cont" :class="[collapseCate ? '':'isActive']">
            <div class="collose-tag collose-pos" v-if="cateHeight > 60" @click="collapseCate = !collapseCate">{{collapseCate ? '收起':'展开'}} <i :class="[collapseCate ? 'el-icon-arrow-up':'el-icon-arrow-down']"></i></div>
            <div class="cont-item" ref="refCategory">
              <a v-for="(item, index) in categoryList" @click="clickCondi(item, 1)" :key="index" class="cont-item_a" :class="{'active': item.id === Number(categoryIds)}" :data-id="item.id" >
                {{item.name}}
              </a>
            </div>
          </section>
        </div>

        <div class="category-row" v-if="otherList.length > 0">
          <span class="category-tit">商品属性</span>
          <section class="category-cont" :class="[collapseOther ? '':'isActive']">
            <div class="collose-tag collose-pos" v-if="otherHeight > 60"  @click="collapseOther = !collapseOther">{{collapseOther ? '收起':'展开'}} <i :class="[collapseOther ? 'el-icon-arrow-up':'el-icon-arrow-down']"></i></div>
            <div class="cont-item brand-item" ref="refProperty">
              <a class="cont-item_a" v-for="other in otherList" :key="other"
              :class="{'active': other === others}" @click="clickCondi(other, 2)">{{other}}</a>
            </div>
          </section>
        </div>
      </div>
    </section>
    </div>
    <!-- 内容 -->
    <section class="search-content knife_container">
      <brandProductItem class="product-box" :product = "goodsObj.list" v-if="goodsObj.list && goodsObj.list.length > 0" :fielsStatus="fielsStatus" :actDate="actDate" :actTime="actTime" :discount="discount"></brandProductItem>
      <div class="no-content" v-else>
        暂无商品~
      </div>
      <!-- pagination -->
      <el-row v-if="goodsObj.page && goodsObj.page.totalPages > 1">
        <el-pagination class="page_box" background layout="total, prev, pager, next, ->" :current-page="goodsPro.page"
          :total="goodsObj.page.totalRecords - 0" :page-size="goodsObj.page.pageSize - 0" @current-change="handlePage" ></el-pagination>
      </el-row>
    </section>
    <!-- 爆品 -->
    <div class="knife_container">
      <HotProduct></HotProduct>
    </div>
  </div>
</template>

<script>
import { getCategoryListByKeyword, getOtherListByKeyword, getGoodsListByKeyword } from '@/service/get-data'
import { Pagination, Row, Input } from 'element-ui'
import { brandProductItem, HotProduct } from '@/components/index'
import { mapState, mapActions } from 'vuex'
import { countDown } from '@/tool/tool'
import { prefixImg } from '@/tool/index'
export default {
  components: {
    elPagination: Pagination,
    elRow: Row,
    elInput: Input,
    brandProductItem,
    HotProduct
  },
  data () {
    return {
      prefixImg,
      timerresult: '',
      timerText: '',
      fielsStatus: 0, // 活动状态  0：未开启， 1： 进行中 2 ：活动结束
      openedActList: null,
      actDate: '',
      actTime: '',
      discount: this.$route.query.discount - 0 || 0,
      categoryName: '',
      brandIds: this.$route.query.brandId - 0 || this.$store.brandId,
      categoryList: [],
      categoryIds: '',
      otherList: [],
      others: '',
      collapseCate: false, // 分类是否展开
      collapseBrand: false, // 品牌是否展开
      collapseOther: false, // 其他属性是否展开
      goodsPro: {
        page: 1, // 商品列表的页码
        number: 20 // 商品列表一页的数量
      },
      amount: 0,
      searchInput: '',
      keyword: '',
      selectType: '', // 主选0为品牌，1为类目
      goodsObj: {}, // 商品列表
      brandHeight: '', // 品牌的高度
      cateHeight: 62, // 类目的高度
      otherHeight: '' // 其他属性的高度
    }
  },
  computed: {
    ...mapState({
      username: state => state.user.username
    }),
    dayNum () {
      return (this.timerresult && this.timerresult.substr(0, 1) - 0) || 0
    }
  },
  methods: {
    ...mapActions(['fetchBrandActivity']),
    getBrandsProduct () {
      this.fetchBrandActivity().then(res => {
        this.openedActList = null
        this.openedActList = (res && res.voList[0]) || {}
        // 周周活动结束
        if (!('id' in this.openedActList)) {
          this.showActivity = false
          return
        }
        let _str = this.openedActList.startTime.split(' ')[0].split('-')
        let _time = this.openedActList.endTime.split(' ')[1].substr(0, 5)
        this.actDate = `${_str[1]}月${_str[2]}日启动 敬请期待`
        this.actTime = _time
        this.brandIds = this.brandIds || this.openedActList.brandVOS[0]['id']
        this.discount = this.discount || this.openedActList.brandVOS[0]['discount']
        let startTimeParm = this.openedActList.startTime
        let endTimeParm = this.openedActList.endTime
        const starTimeStamp = (new Date(startTimeParm.replace(/-/g, '/'))).getTime()
        const endTimeStamp = (new Date(endTimeParm.replace(/-/g, '/'))).getTime()
        let nowTime = (new Date()).getTime()
        // 周周活动开始
        if (nowTime > starTimeStamp && nowTime <= endTimeStamp) {
          this.timerText = '距结束'
          this.fielsStatus = 1
          this.startCountFn(endTimeParm)
          return true
        }
        // 周周活动还未开始
        if (nowTime < starTimeStamp) {
          this.timerText = '距开始'
          this.fielsStatus = 0
          this.startCountFn(startTimeParm)
          return true
        }
        // 周周活动结束
        if (nowTime > endTimeStamp) {
          this.fielsStatus = 2
          return true
        }
      })
    },
    // 倒计时 2018-09-10 2018-09-30
    startCountFn (timeParm) {
      let vm = this
      clearInterval(vm.globalTimer)
      vm.globalTimer = null
      vm.globalTimer = setInterval(function () {
        vm.timerresult = countDown(timeParm)
        // 剩余时间<=0
        if (vm.timerresult + '' === 'false') {
          clearInterval(vm.globalTimer)
          vm.globalTimer = null
          setTimeout(() => {
            vm.getBrandsProduct()
          }, 800)
        }
      }, 1000)
    },
    // 通过关键字获取类目列表
    async fetchCategoryList () {
      let res = await getCategoryListByKeyword(this.searchInput, this.brandIds, this.selectType, this.others)
      res = res.data
      if (res.resultCode && res.resultCode === 2000) {
        this.$nextTick(() => {
          this.categoryList = res.data
        })
      }
    },
    // 获取其他属性
    async fetchOtherListByKeyword () {
      let res = await getOtherListByKeyword(this.searchInput, this.categoryIds, this.brandIds, this.selectType)
      res = res.data
      if (res.resultCode && res.resultCode === 2000) {
        this.otherList = res.data
      }
    },
    // 关键字搜索商品
    async fetchGoodsListByKeyword () {
      let isNewKeyword = this.searchInput !== this.previouskey && this.searchedKey !== this.searchInput
      let res = await getGoodsListByKeyword(this.goodsPro.page, this.goodsPro.number, this.searchInput, this.categoryIds, this.brandIds, this.others, isNewKeyword, this.username)
      res = res.data
      if (res.resultCode && res.resultCode === 2000) {
        this.goodsObj = res.data
        this.changeColor(this.goodsObj.list)
        this.amount = res.data.page.totalRecords
        this.searchedKey = this.searchInput
      }
    },
    // 商品列表分页
    handlePage (page) {
      this.goodsPro.page = page
      this.fetchGoodsListByKeyword()
    },
    // 规格页码选择
    page (currentPage) {
      this.searchPro.page = currentPage
      this.fetchProSpecList()
    },
    // 关键字高亮
    changeColor (resultsList) {
      resultsList.map((item, index) => {
        if (this.searchInput && this.searchInput.length > 0) {
          let replaceReg = new RegExp(this.searchInput, 'g')
          let repalceStr = `<span class="color-red">${this.searchInput}</span>`
          resultsList[index].originname = item.name
          resultsList[index].name = item.name.replace(replaceReg, repalceStr)
          resultsList[index].other = item.other.replace(replaceReg, repalceStr)
          resultsList[index].brandName = item.brandName.replace(replaceReg, repalceStr)
        }
      })
      this.goodsObj.list = []
      this.goodsObj.list = resultsList
    },
    // 点击属性或者分类
    clickCondi (item, type) {
      this.selectType = type
      if (type === 1) {
        this.categoryIds = item.id
        this.categoryName = item.name
        this.fetchOtherListByKeyword()
      } else if (type === 0) {
        this.brandIds = item.id
      } else {
        this.others = item
        this.fetchCategoryList()
      }
      this.goodsPro.page = 1 // 页码设置为1
      this.fetchGoodsListByKeyword()
    },
    // 删除过滤条件
    clearCon (name) {
      if (name === 'categoryName') {
        this.categoryIds = ''
      }
      this[name] = ''
      this.getAllData()
    },
    // 切换品牌
    chooseCon (id, index) {
      this.goodsPro.page = 1 // 页码设置为1
      this.brandIds = id
      this.searchInput = ''
      this.others = ''
      this.categoryIds = ''
      this.discount = this.openedActList.brandVOS[index]['discount']
      this.getAllData()
    },
    blurGetAllData () {
      console.log('blur')
      this.$refs.searchRef.blur()
      this.getAllData()
    },
    getAllData () {
      this.fetchGoodsListByKeyword()
      this.fetchCategoryList()
      this.fetchOtherListByKeyword()
    }
  },
  mounted () {
    let vm = this
    this.getBrandsProduct()
    setTimeout(() => {
      vm.getAllData()
    }, 800)
  },
  beforeRouteLeave (to, from, next) {
    this.globalTimer = null
    clearInterval(this.globalTimer)
    next()
  },
  watch: {
     // 高度监测
    otherList: {
      handler (newValue, oldValue) {
        this.$nextTick(() => {
          if (this.$refs.refProperty) {
            let height = this.$refs.refProperty.offsetHeight
            this.otherHeight = height
          }
        })
      },
      immediate: true
    },
    categoryList: {
      handler (newValue, oldValue) {
        this.$nextTick(() => {
          if (this.$refs.refCategory) {
            let height = this.$refs.refCategory.offsetHeight
            console.log(`高度${height}`)
            this.cateHeight = height
          }
        })
      },
      immediate: true
    }
  },
  filters: {
  }
}
</script>

<style lang="scss" scoped>
.activity-body{
  background:#FDE7DE;
  padding-bottom: 30px;
}
.activity-ad{
  width: 100%;
  height: 580px;
  margin-bottom: 30px;
  background-image: url("./img/brandsale_banner.png");
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
}
.condition-brand-box{
  width:1200px;
  margin: 30px auto 0;
  background: #ffffff;
}
  //搜索
  .activity-search-box{
    float: right;
    vertical-align: middle;
    position: absolute;
    right: 20px;
    top: 0;
    width: 380px;
    height: 35px;
    line-height: 35px;
    background: rgba(235,235,235,1);
    border-radius: 5px;
    overflow: hidden;
    padding-left: 15px;
    .search_posi{
      font-size: 16px;
    }
    .search_input{
      width: 70%;
      font-size: 14px;
      background: rgba(235,235,235,1);
    }
    .search_sure{
      float: right;
      width: 87px;
      height: 35px;
      line-height: 37px;
      background: rgba(251,205,59,1);
      text-align: center;
      color: #333333;
      cursor: pointer;
    }
  }
.activity-head-box{
  height: 50px;
  line-height: 50px;
  background: #D4230F;
  padding: 0 20px;
  color: #fff;
  box-sizing: border-box;
  .smalltitle{
    font-size: 18px;
    padding-right: 20px;
  }
  .discount-box{
    font-size: 18px;
    padding: 4px 16px;
    color: #FF0000;
    background: #ffffff;
    border-radius: 2px;
    line-height:28px;
  }
}
.brand-head-box{
  background: #CF0930;
  .smallright{
    float:right;
    color:rgba(243,183,183,1);
    font-size:18px;
  }
}
.condition-wrapper{
  overflow: hidden;
  margin-top: 27px;
  height: 44px;
  padding-left: 20px;
  .brand-input-box{
    width: 272px;
    height: 35px;
    border: none;
    background: #ebebeb;
  }
}
.condition-box{
  display: inline-block;
}
.condition-txt{
  color:#767676;
  font-size: 12px;
  padding: 3px;
}
.brand-alternative-box{
  height: 85px;
  line-height: 85px;
  .b-item{
    width: 600px;
    text-align: center;
    display: inline-block;
    font-size: 28px;
    color: #999999;
    background: #e2e2e2;
    cursor: pointer;
  }
  .brandimg{
    margin: 0 10px;
    height: 48px;
    max-width: 180px;
    vertical-align: middle;
    filter: grayscale(100%);
  }
}
.active{
  color:#D4230F!important;
  background: #fff!important;
  .brandimg{
    filter: grayscale(0);
    filter: gray;
  }
}
.category-box {
  position: relative;
  margin-bottom: 20px;
  .category-item{
    border: 1px solid #e6e6e6;
  }
  .category-row{
    overflow: hidden;
    // display: flex;
    border-bottom: 1px solid #e6e6e6;
    // justify-content: flex-start;
    transition: all 0.3s;
    background: #404040;
    &:last-child{
      border-bottom: none;
    }
  }
  
  .category-tit {
    // display: table-cell;
    background: #404040;
    text-align: center;
    color: #fff;
    width:90px;
    line-height: 60px;
    font-size: 14px;
    float: left;
  }
  .category-cont{
    // display: table-cell;
    position: relative;
    // flex: 1;
    background: #fff;
    height: auto;
        margin-left: 90px;
  }
  .cont-item {
    // width: 1110px;
    //height: 60px;
    // line-height: 60px;
    border-bottom: 1px solid #e6e6e6;
    padding: 10px 150px 10px 0;
    &:last-child {
      border-bottom: none;
    }
  }
  .cont-item_a{
    color: #666;
    font-size: 14px;
    display: inline-block;
    padding: 13px 30px 13px 32px;
    &.active{
      color:#FFCC00;
    }
  }
    .isActive{
    height: 60px;
    overflow: hidden;
  }
}
.collose-tag{
  font-size: 12px;
  color: #2377E0;
  cursor: pointer;
  width: 60px;
  height: 30px;
  line-height: 30px;
  text-align: center;
}
.collose-pos{
  position: absolute;
  right: 10px;
  top: 15px;
}
// 倒计时
.text-time{
  margin-right: 10px;
}
.acti_entry_timer{
  display:inline-block;
  position: absolute;
  margin-top: 5px;
  line-height: 30px;
  .timer-text{
    color:#fff;
    line-height:53px;
    font-size:28px;
    vertical-align: middle;
  }
  .week-time{
    font-family: PingFangSC-Semibold, Microsoft YaHei;
    font-weight: 600;
    background: #ffffff;
    border-radius: 4px;
    width: 42px;
    height: 35px;
    display: inline-block;
    vertical-align: middle;
    color: #000;
    font-size: 20px;
    line-height: 35px;
    text-align: center;
    letter-spacing: 2px;
  }
  .week-colon {
    font-size: 20px;
    line-height: 40px;
    vertical-align: middle;
    display: inline-block;
  }
}
</style>
<style lang="scss">
  .brand-input-box{
    .el-input__inner{
      border: none;
      background: #ebebeb;
      height: 35px;
      line-height: 35px;
    }
  }
</style>

